const path = require('path');
const fs = require('fs');
const apps = require('./app-build-info');


const appBuildInfos = [];

const customLibrary = "./custom-lib";
const projectFolder = "./app";
const projectEntryFolder = "/src";
const projectConfig = "/app-config.json";

for (const app of apps) {

    const appPath = path.join(__dirname, projectFolder + '/' + app);

    const appConfig = JSON.parse(fs.readFileSync(path.join(appPath, "/" + projectEntryFolder + "/" + projectConfig)));

    appConfig.containerPath = appConfig.containerPath || "./app-container.tsx";
    appConfig.containerName = appConfig.containerName || "AppContainer";
    appConfig.entry = appConfig.entry || "./app.js";
    appConfig.output = appConfig.output || "./dist";
    appConfig.asset = appConfig.asset || "./asset";
    appConfig.icon = appConfig.icon || "./favicon.ico";
    appConfig.uiType = appConfig.uiType || "";
    appConfig.copyDirectory = appConfig.copyDirectory || "";
    appConfig.pasteDirectory = appConfig.pasteDirectory || appConfig.output;

    let useAllExtension = false;
    switch (appConfig.uiType) {
        case "react":
            useAllExtension = false;
            break;
        case "vue":
            useAllExtension = true;
            break;
    }

    let ary = projectEntryFolder.split('/');
    const src = ary[ary.length - 1];
    ary = appConfig.asset.split('/');
    const asset = ary[ary.length - 1];
    ary = customLibrary.split('/');
    const library = ary[ary.length - 1];

    const appBuildInfo = {
        name: appConfig.name,
        containerPath: appConfig.containerPath,
        containerName: appConfig.containerName,
        entry: path.join(appPath, projectEntryFolder, appConfig.entry),
        output: path.join(appPath, appConfig.output),
        path: appPath,
        src: src,
        asset: asset,
        library: library,
        icon: path.join(appPath, projectEntryFolder, appConfig.icon),
        useAllExtension: useAllExtension,
        copyDirectory: appConfig.copyDirectory ? path.join(appPath, appConfig.copyDirectory) : "",
        pasteDirectory: path.join(appPath, appConfig.pasteDirectory),
    };

    let entry = fs.readFileSync(path.join(__dirname, "template/app-entry.js.template"), { encoding: "utf8" });
    entry = entry.replace(/\[#containerName#\]/g, appConfig.containerName);
    entry = entry.replace(/\[#containerPath#\]/g, appConfig.containerPath);

    fs.writeFileSync(appBuildInfo.entry, entry, { encoding: 'utf8', flag: 'w' });

    appBuildInfos.push(appBuildInfo);
}



module.exports = appBuildInfos;